package com.bite.forum.controller;

import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.config.AppConfig;
import com.bite.forum.model.Article;
import com.bite.forum.model.User;
import com.bite.forum.services.IArticleService;
import com.bite.forum.services.IUserService;
import com.bite.forum.services.PictureService;
import com.bite.forum.utils.MD5Util;
import com.bite.forum.utils.StringUtil;
import com.bite.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: dimimgluo
 * @CreateTime: 2024-11-09  17:45
 * @Description: TODO
 */

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private PictureService pictureService;
    @Resource
    private IArticleService articleService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password,salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        userService.createNormalUser(user);
        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        // 调用 userService 的 login 方法校验用户名和密码
        User user = userService.login(username, password);
        if (user == null) {
            // 登录失败，记录警告日志并返回失败结果
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        // 登录成功，创建会话并保存用户信息到 session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 返回成功结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo (HttpServletRequest request,
           @ApiParam("用Id") @RequestParam(value = "id",required = false) Long id){
    User user = null;
    if(id == null){
        HttpSession session = request.getSession(false);
        user = (User) session.getAttribute(AppConfig.USER_SESSION);
    }else {
        user = userService.selectById(id);
    }
    if(user == null){
        return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
    }
    return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session != null){
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                 @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                 @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                 @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark) {
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        userService.modifyInfo(updateUser);

        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success(user);
    }

    @ApiOperation("更新头像")
    @PostMapping("/uploadAvatar")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @RequestParam("avatarFile") MultipartFile avatarFile) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        String fileName = pictureService.savePicture(avatarFile);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setAvatarUrl(fileName);
        userService.modifyInfo(updateUser);
        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        if (!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }

    /**
     * 获取用户收藏列表
     */
    @GetMapping("/favorites")
    public AppResult<List<Article>> getUserFavorites(HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        List<Article> favorites = articleService.getFavoritesByUserId(user.getId());
        return AppResult.success(favorites);
    }
}
